import axios from 'axios';
import Config from '../../config';
import Web3Manager from '../../libs/web3-manager';
import Authentication from '../authentication/authentication';

interface CheckOTPResponse {
    authentication : Authentication;
    error : string;
}

interface SendOTPResponse {
    sent? : boolean;
    timeRemaining ? : number;
}


export default class OTPManager {

    static Endpoint = {
        SEND : '/otp/send',
        CHECK : '/otp/check'
    }

    static send = async () : Promise<SendOTPResponse> => {
        try {
            const call = await axios.post(Config.getAPI() + OTPManager.Endpoint.SEND, {
                'wallet_address' : await Web3Manager.getWalletAddress()
            });
    
            if(call.data['sent']) {
                return {
                    sent: call.data['sent']
                };
            }

            if(call.data['time_remaining']) {
                return {
                    timeRemaining : call.data['time_remaining']
                }
            }
        } catch(exception) {
            console.log(exception);
        }

        return null;
    }

    static check = async (otp : string) : Promise<CheckOTPResponse> => {
        try {
            const call = await axios.post(Config.getAPI() + OTPManager.Endpoint.CHECK, {
                'wallet_address' : await Web3Manager.getWalletAddress(),
                'otp' : otp
            });
    
            if(call.data['authentication-key'] && call.data['authentication-secret']) {
                const authentication = new Authentication();
                authentication.key = call.data['authentication-key'];
                authentication.secret = call.data['authentication-secret'];
                return {
                    authentication: authentication,
                    error: null
                };
            } else if(call.data['error'] && call.data['error']['message']) {
                return {
                    authentication: null,
                    error: call.data['error']['message']
                };
            }
        } catch(exception) {
            console.log(exception);
        }

        return null;
    }
}